<style lang="scss">
.ivu-modal-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  .ivu-modal{
    top: 0;
  }
}
</style>
<template>
  <div class="content">
    <Breadcrumb>
      <BreadcrumbItem to="/index">首页</BreadcrumbItem>
      <BreadcrumbItem>试题管理</BreadcrumbItem>
    </Breadcrumb>
    <Form inline :label-width="70" label-position="left" :model="search" v-if="treeData.length">
      <Button type="success" style="margin-right: 30px" @click="addModal = true">添加</Button>
      <FormItem label="题目">
        <Input type="text" v-model="search.name" placeholder="请输入题目检索"/>
      </FormItem>
      <FormItem label="科目">
        <Select type="text" v-model="search.subject.parentId" placeholder="请选择科目检索" clearable>
          <Option v-for="tree in treeData[0].children" :value="tree.id" :key="tree.id">{{ tree.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="课程">
        <Select type="text" v-model="search.subjectId" placeholder="请选择课程检索" clearable>
          <Option v-for="tree in subjectData" :value="tree.id" :key="tree.id">{{ tree.name }}</Option>
        </Select>
      </FormItem>
      <Button type="primary" style="margin-left: 30px" @click="searchClick">搜索</Button>
    </Form>
    <Table stripe row-key="id" :columns="columns" :data="data"></Table>
    <Page :current="current" :total="total" :page-size="pageSize" show-total show-sizer show-elevator :styles="{marginTop: '20px'}" @on-change="pageChange" @on-page-size-change="pageSizeChange" />
    <Modal
      v-model="modalShow"
      :title="addModal ? '添加试题' : editModal ? '修改试题' : '' + '灵异试题'"
      cancel-text="取消"
      class-name="center-modal"
      @on-visible-change="modalChange">
      <Form :model="form" :label-width="80" ref="modalForm" :rules="rules">
        <FormItem label="题目" prop="name">
          <Input v-model="form.name" placeholder="请输入题目"/>
        </FormItem>
        <FormItem label="科目" prop="subjectName">
          <input v-model="form.subjectName" placeholder="请点击选择科目" readonly @click="subjectTree = true" class="ivu-input ivu-input-default"/>
          <input v-model="form.subjectId" type="hidden"/>
        </FormItem>
        <FormItem label="选项" prop="correct" v-if="form.options.length">
          <RadioGroup v-model="form.correct" vertical style="width: 100%;">
            <Radio v-for="(opt, index) in form.options" :label="opt.label" style="margin-bottom: 30px;" :key="opt.label">
              <FormItem style="display: inline-block;width: 92%;" :prop="'options.' + index + '.content'" :rules="[
                  {
                    required: true,
                    type: 'string',
                    message: '选项不能为空',
                    trigger: 'blur'
                  },
                  {
                    min: 1,
                    max: 500,
                    message: '选项长度在1-500位之间',
                    trigger: 'blur'
                  }
                ]">
                <span style="margin-right: 10px;">{{ opt.label }}</span>
                <Input v-model="form.options[index].content" placeholder="请输入选项"></Input>
              </FormItem>
            </Radio>
          </RadioGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" size="large" @click="modalShow = false">取消</Button>
        <Button type="primary" size="large" @click="submit">{{ addModal ? '添加' : editModal ? '修改' : '' + '灵异' }}</Button>
      </div>
    </Modal>
    <Modal
        v-model="subjectTree"
        title="树形菜单"
        cancel-text="取消"
        class-name="center-modal"
        :z-index="99999"
        @on-cancel="subjectTree = false">
      <Tree :data="treeData" @on-select-change="selectChange"></Tree>
      <div slot="footer">
        <Button type="primary" size="large" @click="subjectTreeOkClick">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: 'Question',
  data: function () {
    return {
      columns: [
        {
          type: 'index'
        },
        {
          title: '题目',
          key: 'name'
        },
        {
          title: '科目',
          render: (h, params) => {
            return h('div', {}, params.row.subject.parentName + ' ' + params.row.subject.name)
          }
        },
        {
          title: '正确答案',
          key: 'correct'
        },
        {
          title: '创建时间',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: '200px',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.form = { ...params.row }
                    this.form.options = JSON.parse(JSON.stringify(params.row.options))
                    this.form.subjectName = params.row.subject.parentName + ' ' + params.row.subject.name
                    this.editModal = true
                  }
                }
              }, '修改'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '删除提示',
                      content: '是否确认删除?',
                      okText: '确定',
                      cancelText: '取消',
                      onOk: () => {
                        this.$http.delete(`questions?id=${params.row.id}`).then(res => {
                          if (res.code === 200) {
                            this.getData()
                            this.$Message.success(res.msg)
                          }
                        })
                      }
                    })
                  }
                }
              }, '删除')
            ])
          }
        }
      ],
      data: [],
      addModal: false,
      editModal: false,
      form: {
        options: []
      },
      rules: {
        name: [
          {
            required: true,
            type: 'string',
            message: '题目不能为空',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 200,
            message: '题目长度在1-200位之间',
            trigger: 'blur'
          }
        ],
        correct: [
          {
            required: true,
            type: 'string',
            message: '请选择一个正确答案',
            trigger: 'blur'
          }
        ],
        subjectName: [
          {
            required: true,
            type: 'string',
            message: '科目不能为空',
            trigger: 'blur'
          }
        ],
        options: [
          {
            type: 'array',
            required: true,
            defaultField: {
              type: 'object',
              require: true,
              fields: {
                content: [
                  {
                    required: true,
                    type: 'string',
                    message: '选项不能为空',
                    trigger: 'blur'
                  },
                  {
                    min: 1,
                    max: 500,
                    message: '选项长度在1-500位之间',
                    trigger: 'blur'
                  }
                ]
              }
            }
          }
        ]
      },
      total: 0,
      current: 1,
      pageSize: 10,
      search: {
        subject: {}
      },
      parentData: {},
      treeData: [],
      subjectTree: false
    }
  },
  mounted () {
    for(let i = 0; i < 4; ++i) this.form.options.push({ content: '', label: String.fromCharCode(65 + i) });
    this.getData()
  },
  computed: {
    modalShow: {
      get () {
        return this.addModal || this.editModal
      },
      set () {
        this.addModal = this.editModal = false
      }
    },
    subjectData() {
      if(this.search.subject.parentId != null && this.search.subject.parentId !== '') {
        return this.treeData[0].children.filter(v => (v.id === this.search.subject.parentId))[0].children;
      }
      return [];
    }
  },
  methods: {
    getData () {
      this.$http.post(`question/get?pageNo=${this.current}&pageSize=${this.pageSize}`, this.search).then(res => {
        this.current = res.data.page.current
        this.total = res.data.page.total
        this.data = res.data.page.records
      });
      this.$http.get("subject/tree").then(res => {
        this.treeData = res.data.tree
      })
    },
    modalChange (v) {
      if (!v) {
        this.$refs.modalForm.resetFields()
        this.form = { options: [] }
        for (let i = 0; i < 4; i++) this.form.options.push({ content: '', label: String.fromCharCode(65 + i) })
        console.log(this.form.options)
      }
    },
    submit () {
      this.$refs.modalForm.validate((v) => {
        if (v) {
          if (this.addModal) {
            console.log(this.form)
            this.$http.post('questions', this.form).then(res => {
              if (res.code === 200) {
                this.getData()
                this.$Message.success(res.msg)
                this.addModal = false
              }
            })
          }
          if (this.editModal) {
            this.form.updateTime = null
            this.$http.put('questions', this.form).then(res => {
              if (res.code === 200) {
                this.getData()
                this.$Message.success(res.msg)
                this.editModal = false
              }
            })
          }
        }
      })
    },
    status (obj) {
      this.$http.post('question/status', this.form).then(res => {
        if (res.code === 200) {
          this.$Message.success(res.msg)
          obj.row.status = status
        }
      })
    },
    pageChange (index) {
      this.current = index
      this.getData()
    },
    pageSizeChange (size) {
      this.current = 1
      this.pageSize = size
      this.getData()
    },
    searchClick () {
      this.current = 1
      this.getData()
    },
    selectChange (arr, obj) {
      this.parentData.id = obj.id
      this.parentData.name = obj.name
      this.parentData.parentName = obj.parentName
    },
    subjectTreeOkClick () {
      this.form.subjectId = this.parentData.id
      this.form.subjectName = this.parentData.parentName + ' ' + this.parentData.name
      this.subjectTree = false
    }
  }
}
</script>

<style scoped lang="scss">
form {
  margin-top: 20px;
}
</style>
